import { Request, Response } from 'express';
import { UserService } from '../services/user.service';

const userService = new UserService();

export class UserController {
    async login(req: Request, res: Response) {
        const { username, password } = req.body;
        
        if (!username || !password) {
            return res.status(400).json({ message: '用户名和密码不能为空' });
        }

        try {
            const user = await userService.login(username, password);
            if (!user) {
                return res.status(401).json({ message: '用户名或密码错误' });
            }
            res.json({ message: '登录成功', data: user });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async register(req: Request, res: Response) {
        const { username, password, name, email } = req.body;

        if (!username || !password || !email) {
            return res.status(400).json({ message: '用户名、密码和邮箱为必填项' });
        }

        try {
            const user = await userService.register({ username, password, name, email });
            if (!user) {
                return res.status(400).json({ message: '用户名已存在' });
            }
            res.status(201).json({ 
                message: '注册成功', 
                data: user 
            });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async getUserInfo(req: Request, res: Response) {
        try {
            // 实际项目中应该从token中获取userId
            const userId = 1; // 模拟已登录用户
            const user = await userService.getUserInfo(userId);
            
            if (!user) {
                return res.status(404).json({ message: '用户不存在' });
            }

            res.json({ data: user });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }

    async updateUserInfo(req: Request, res: Response) {
        try {
            // 实际项目中应该从token中获取userId
            const userId = 1; // 模拟已登录用户
            const updateData = req.body;

            const updatedUser = await userService.updateUserInfo(userId, updateData);
            
            if (!updatedUser) {
                return res.status(404).json({ message: '用户不存在' });
            }

            res.json({ 
                message: '更新成功',
                data: updatedUser 
            });
        } catch (error) {
            res.status(500).json({ message: '服务器错误' });
        }
    }
}
